package sbt.transformation;

import java.util.HashMap;
import java.util.Map;

import sbt.metamodel.Obsel;
import sbt.metamodel.TransformationMethod;

/**
 * I provide base functionality for TransformationMethods whose main purpose
 * is to copy (a subset of) the obsels of sources in the target trace.
 * @author pa
 *
 */
public abstract class AbstractCopier extends TransformationMethod {
	
	// mapping sourceObsel.id to targetObsel 
	Map<Obsel, Obsel> copiedObsels = new HashMap<Obsel, Obsel>();
	
	@Override
	protected void clearTargetObsels() {
		super.clearTargetObsels();
		copiedObsels.clear();
	}
	
	/**
	 * Create in the target trace a copy of the given obsel.
	 * @param o
	 */
	protected Obsel copyObsel(Obsel o) {
		Obsel ret = createObsel(o.getType(), o.getBegin(), o.getEnd(),
				o.getSubject(), o.getAttributes(),
				mapRelations(o.getRelated()),
				mapRelations(o.getRelating()));
		copiedObsels.put(o, ret);
		return ret;
	}

    /**
     * Translate a map of related/ing to the copied obsels in the target trace.
     */
	protected Map<String, Obsel> mapRelations(Map<String, Obsel> map) {
		Map<String, Obsel> ret = new HashMap<String, Obsel>();
		for (Map.Entry<String, Obsel> e: map.entrySet()) {
			Obsel mappedObsel = copiedObsels.get(e.getValue());
			if (mappedObsel != null) {
				ret.put(e.getKey(), mappedObsel);
			}
		}
		return ret;
	}

}
